package com.application.net;

import com.application.common.BaseContext;
import com.application.common.BaseLogger;
import com.application.common.Lock;
import com.application.common.LockHolder;
import com.application.config.BaseConfig;
import com.application.config.ConfigNetwork;
import com.application.iface.IMessage;
import com.application.iface.IPacket;

public class TcpAdapter {
	public static void sendResponse(String msg) {

		// 获取 发送IP
		ConfigNetwork cn = BaseConfig.getInstance().getBestRemote();
		if (cn == null) {
			BaseLogger.writeLog("E", "尚未注册ESB服务器");
		}

		try {
			cn.runClient(msg);
		} catch (Exception e) {
			BaseLogger.writeLog("E", "发送失败:" + msg);
		}
		
		BaseLogger.writeLog("I", "发送成功");
	}
	public static IMessage send(IMessage msg) throws Exception {
		IMessage res = null;
		// 获取 发送IP
		ConfigNetwork cn = BaseConfig.getInstance().getBestRemote();
		if (cn == null) {
			BaseLogger.writeLog("E", "尚未注册ESB服务器");
			throw new Exception("尚未注册ESB服务器");
		}

		try {
			//默认json 格式
			IPacket pack = (IPacket) BaseContext.context.getBean("JsonPacket");
			cn.runClient(pack.getData( msg));
		} catch (Exception e) {
			BaseLogger.writeLog("E", "发送失败:" + msg);
			throw new Exception(e);
		}
		BaseLogger.writeLog("I", "发送成功,等待响应");
		Lock lock = new Lock();
		LockHolder.addLock(msg.getUniqueId(), lock);
		synchronized(lock){
			try{
				if(!lock.isNotified()){
					lock.wait(cn.getTimeout());
				}				
			}catch (InterruptedException e){
				BaseLogger.writeLog("E", "线程中断:");
				throw new Exception(e);
			}
            res = lock.getJsonMessage();
			
		}
		return res;
	}
	
	public static IMessage send(ConfigNetwork cn,IPacket pack,IMessage msg) throws Exception {
		IMessage res = null;

		try {
			//默认json 格式
			cn.runClient(pack.getData( msg));
		} catch (Exception e) {
			BaseLogger.writeLog("E", "发送失败:" + msg);
			throw new Exception(e);
		}
		BaseLogger.writeLog("I", "发送成功,等待响应");
		Lock lock = new Lock();
		LockHolder.addLock(msg.getUniqueId(), lock);
		synchronized(lock){
			try{
				if(!lock.isNotified()){
					lock.wait(cn.getTimeout());
				}				
			}catch (InterruptedException e){
				BaseLogger.writeLog("E", "线程中断:");
				throw new Exception(e);
			}
            res = lock.getJsonMessage();
			
		}
		return res;
	}
}
